package cn.kgc.javaweb.servlet;

import cn.kgc.javaweb.entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;

/**
 * @author: mosin
 * @version: v1.0  2022/10/25
 */
@WebServlet("/table")  //  通过注解取代配置的方式  实现servlet的声明
public class TableServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 响应一个表格给前端浏览器  html   username  password  address
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String address = req.getParameter("address");

        System.out.println("address = " + address);
        System.out.println("username = " + username);
        System.out.println("password = " + password);

        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setAddress(address);

        // 将user对象封装到集合

        ArrayList<User> users = new ArrayList<>();
        Collections.addAll(users, user,user,user,user);

        // 将获取的参数 响应成一个表格给前端浏览器  json
        resp.setContentType("text/html;charset=utf-8");

        PrintWriter writer = resp.getWriter();
        writer.write("<table  border=\"1\" cellspacing=\"0\" width=\"100%\">");

        writer.write(" <tr>");
        writer.write("<th>用户名</th>");
        writer.write("<th>密码</th>");
        writer.write("<th>地址</th>");
        writer.write("</tr>");

        //  通过 查询数据库 将查询的结果响应给浏览器  List
        users.forEach(usr->{
            writer.write(" <tr>");
            writer.write("<td>"+usr.getUsername()+"</td>");
            writer.write("<td>"+usr.getPassword()+"</td>");
            writer.write("<td>"+usr.getAddress()+"</td>");
            writer.write("</tr>");
        });

        writer.write("</table>");
        // 关闭流 释放资源
        writer.close();

    }
}
